package me.dengfengdecao.demo.web;

import me.dengfengdecao.demo.domain.User;
import me.dengfengdecao.demo.utils.Const;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by dengfengdecao on 16/9/27.
 */
@Controller
public class FileController {

    public static final Logger log = LoggerFactory.getLogger(FileController.class);

    @RequestMapping(value = "/file", method = RequestMethod.GET)
    public String toUploadFileUI() {
        return "upload-file";
    }

    @RequestMapping(value = "/file", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadFile(User user, @RequestParam("files")MultipartFile[] parts) {
        Map<String, Object> map = new LinkedHashMap<String, Object>();

        for (MultipartFile part : parts) {
            if (!part.isEmpty()) {
                log.debug("uploadFile: OriginalFilename : " + part.getOriginalFilename());
                log.debug("uploadFile: Filename : " + part.getName());
                log.debug("uploadFile: contentType : " + part.getContentType());

                File dest = new File("/Users/dengfengdecao/Documents", part.getOriginalFilename());
                try {
                    part.transferTo(dest);
                } catch (IOException e) {
                    log.error("uploadFile: " + e.getMessage());
                }
            /*FileOutputStream fos = new FileOutputStream(dest, true);
            BufferedOutputStream out = new BufferedOutputStream(fos);
            out.write(part.getBytes());
            out.flush();
            out.close();*/
                map.put(Const.SUCCESS_RESPONSE, "上传成功!");
            } else {
                map.put(Const.FAIL_RESPONSE, "上传失败,因为文件是空的.");
            }
        }
        return map;
    }
}
